extern "C"
{
#include <windows.h>
}
#include "NetworkCommonFunction.h"
#include "CommProgram.h"

#include <boost/scoped_array.hpp>
#include <QTime>
#include <QString>
#include <QDebug>

bool CorrectTimeHandler(int socket, int commandLength)
{
	qDebug()<<"Receive Correct time command";

	const int bufferSize = 500 * 1024;
	char* buffer = new char[bufferSize];
	boost::scoped_array<char> bufferContainer(buffer);

	if(!receiveData(socket, buffer, commandLength))
	{
		qDebug()<<"Receive time error";
		return false;
	}

	buffer[commandLength] = 0;
	QString timeString(buffer);
	QDateTime dateTime = QDateTime::fromString(timeString, "yyyy-MM-dd hh:mm:ss");
	QDate date = dateTime.date();
	QTime time = dateTime.time();

	qDebug()<<"Correct time:"<<timeString;

	SYSTEMTIME systemTime;
	ZeroMemory(&systemTime, sizeof(systemTime));
	systemTime.wYear = date.year();
	systemTime.wMonth = date.month();
	systemTime.wDay = date.day();
	systemTime.wDayOfWeek = date.dayOfWeek();
	systemTime.wHour = time.hour();
	systemTime.wMinute = time.minute();
	systemTime.wSecond = time.second();

	if(!SetLocalTime(&systemTime))
	{
		qDebug()<<"Reset time error";
	}
	else
	{
		qDebug()<<"Set time successful";
	}

	InitialTime();

	return true;
}
